package com.xishu.controller;

import com.xishu.config.Config;
import com.xishu.entity.shop.FoodTable;
import com.xishu.entity.shop.Shop;
import com.xishu.response.ResponseData;
import com.xishu.response.VerifyUtil;
import com.xishu.service.*;
import com.xishu.util.ImgService;
import com.xishu.util.MongoId;
import com.xishu.util.ZipUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

@Api(value = "二维码生成器")
@RestController
public class QrCodeController {
    private static Logger logger = LoggerFactory.getLogger(QrCodeController.class);
    private Config config = Config.getInstance();
    private CommonService commonService = CommonService.getInstance();


    @PutMapping(value = ("/food/table/qr/code"), produces = ("application/json;charset=UTF-8"))
    @ApiOperation(value = "餐桌二维码生成,传ID，含义是分店ID")
    public ResponseData foodTableQrCode(@RequestBody Shop shop) throws Throwable {
        //按照链接批量生成二维码文件后，打包上传，生成的时候，按照横纵坐标来生成
        //生成之后的文件名保存在shop上面
        ///pages/menu?sid=1&c=1&r=1&uid=1&type=normal
        Long shopId = shop.getId();
        VerifyUtil.verify(() -> shopId != null);

        Shop shopInDb = ShopService.getInstance().findShopById(shopId);
        File logoFile = CompanyService.getInstance().getCompanyLogoForQrCode(shopInDb.getCompanyId());

        List<FoodTable> defaultFoodTableList = FoodTableService.getInstance().findTemplate(shopId);
        String randomId = MongoId.generateId();

        List<File> fileList = defaultFoodTableList.stream().map(foodTable -> {
            String url = config.getEndPoint() + String.format("/customer/index.html/#/pages/menu?sid=%s&c=%s&r=%s&uid=0&type=normal&ct=%s", shopId, foodTable.getColumn(), foodTable.getRow(), randomId);
            File file = ImgService.getInstance().createLogoQrCode(url, logoFile);

            //按照坐标来生成文件,通过查询模板的CODE值来生成
            List<FoodTable> foodTableList = FoodTableService.getInstance().findTemplate(foodTable.getShopId(), foodTable.getRow(), foodTable.getColumn());

            File foodTableNoFile = null;
            if (commonService.isNotEmpty(foodTableList)) {
                HashSet<String> code = new HashSet<>();
                for (FoodTable table : foodTableList) {
                   code.add(table.getCode());
                }

                String joinCode = StringUtils.join(code, "-");
                foodTableNoFile = new File(config.getUploadTmpPath() + "/" + joinCode + ".png");
            } else {
                foodTableNoFile = new File(config.getUploadTmpPath() + "/" + foodTable.getRow() + "-" + foodTable.getColumn() + ".png");
            }

            FileInputStream fileInputStream = null;
            FileOutputStream fileOutputStream = null;

            try {
                fileInputStream = new FileInputStream(file);
                fileOutputStream = new FileOutputStream(foodTableNoFile);
            } catch (FileNotFoundException e) {
                logger.error("e", e);
            }

            try {
                IOUtils.copy(fileInputStream, fileOutputStream);
            } catch (IOException e) {
                logger.error("e", e);
            } finally {
                IOUtils.closeQuietly(fileInputStream);
                IOUtils.closeQuietly(fileOutputStream);
            }

            return foodTableNoFile;
        }).collect(Collectors.toList());

        //压缩文件
        String[] filePathList = fileList.stream().map(p -> p.getAbsolutePath()).collect(Collectors.toList()).toArray(new String[fileList.size()]);
        File zipFile = MongoId.getInstance().generateTmpFile("zip");
        ZipUtil.zip(filePathList, zipFile.getAbsolutePath());

        //上传到对象存储
        ObjectService.getInstance().uploadObject(zipFile);

        //保存数据
        shopInDb.setFoodTableQrFileId(zipFile.getName());
        shopInDb.setFoodTableQrQc(randomId);
        CommonService.getInstance().save(shopInDb);
        return commonService.createResponse(shopInDb);
    }

    @PutMapping(value = ("/food/qr/code"), produces = ("application/json;charset=UTF-8"))
    @ApiOperation(value = "总二维码生成,传ID，含义是分店ID")
    public ResponseData totalQrCode(@RequestBody Shop shop) throws Throwable {
        Long shopId = shop.getId();
        VerifyUtil.verify(() -> shopId != null);

        String randomId = MongoId.generateId();

        //生成二维码
        String url = config.getEndPoint() + String.format("/customer/index.html/#/pages/menuBefore?sid=%s&ct=%s", shopId, randomId);

        Shop shopInDb = ShopService.getInstance().findShopById(shopId);
        File logoFile = CompanyService.getInstance().getCompanyLogoForQrCode(shopInDb.getCompanyId());

        //上传二维码
        File file = ImgService.getInstance().createLogoQrCode(url, logoFile);
        ObjectService.getInstance().uploadObject(file);

        //保存配置
        shopInDb.setHomeQrFileId(file.getName());
        shopInDb.setTotalQrQc(randomId);
        CommonService.getInstance().save(shopInDb);

        return commonService.createResponse(shopInDb);
    }

    ///pages/lineupForm?sid=1
    @PutMapping(value = ("/line/up/qr/code"), produces = ("application/json;charset=UTF-8"))
    @ApiOperation(value = "排队二维码生成,传ID，含义是分店ID")
    public ResponseData lineupQrCode(@RequestBody Shop shop) throws Throwable {
        Long shopId = shop.getId();
        VerifyUtil.verify(() -> shopId != null);
        String randomId = MongoId.generateId();

        //生成二维码
        String url = config.getEndPoint() + String.format("/customer/index.html/#/pages/lineupForm?sid=%s&ct=%s", shopId, randomId);

        Shop shopInDb = ShopService.getInstance().findShopById(shopId);
        File logoFile = CompanyService.getInstance().getCompanyLogoForQrCode(shopInDb.getCompanyId());

        //上传二维码
        File file = ImgService.getInstance().createLogoQrCode(url, logoFile);
        ObjectService.getInstance().uploadObject(file);

        //保存配置
        shopInDb.setLineUpQc(randomId);
        shopInDb.setLineUpQrFileId(file.getName());
        CommonService.getInstance().save(shopInDb);

        return commonService.createResponse(shopInDb);
    }

}
